package dropoffdesk;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

/**
 * This class opens the drop-off desk after a random delay from the start of the
 * application and handles user events from the drop-off desk GUI
 * 
 * @author Andrew Stokes
 * 
 */
public class DeskController {

	private DropOffDesk desk;

	public DeskController(DeskGUI deskGUI, DropOffDesk desk) {

		this.desk = desk;
		deskGUI.setVisible(true);
		deskGUI.addCloseDeskButtonListener(new CloseDeskButtonListener());

		// open the desk after a random delay - run in a separate thread
		Thread thread = new Thread(new OpenDesk(desk));
		thread.start();

	}

	// private class to open the drop-off desk after a random delay
	private class OpenDesk implements Runnable {
		static final int DELAY_START = 10000;
		DropOffDesk desk;

		OpenDesk(DropOffDesk desk) {
			this.desk = desk;
		}

		public void run() {
			try {
				// wait a random time between 0 and 10s
				Random random = new Random();
				Thread.sleep(random.nextInt(DELAY_START));
				// open the drop-off desk
				desk.setIsOpen(true);
				// start processing the queue
				desk.processQueue();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	// Handle the button event on the GUI and close the drop-off desk
	public class CloseDeskButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			desk.setIsOpen(false);

		}
	}

}
